package com.bb.blog.security.model;

import com.alibaba.druid.util.StringUtils;
import org.apache.ibatis.type.*;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes({List.class})
public class VarcharToGrantList extends BaseTypeHandler<List<SimpleGrantedAuthority>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<SimpleGrantedAuthority> parameter, JdbcType jdbcType) throws SQLException {
        String value;
        if(parameter.isEmpty()){
            value = null;
        }else{
            value = parameter.stream().map(SimpleGrantedAuthority::getAuthority).collect(Collectors.joining(","));
        };
        ps.setString(i,value);
    }

    @Override
    public List<SimpleGrantedAuthority> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        if(StringUtils.isEmpty(value)){
            return Collections.emptyList();
        }
        return Arrays.asList(value.split(",")).stream().map(
                SimpleGrantedAuthority::new
        ).collect(Collectors.toList());
    }

    @Override
    public List<SimpleGrantedAuthority> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        if(StringUtils.isEmpty(value)){
            return Collections.emptyList();
        }
        return Arrays.asList(value.split(",")).stream().map(
                SimpleGrantedAuthority::new
        ).collect(Collectors.toList());
    }

    @Override
    public List<SimpleGrantedAuthority> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        if(StringUtils.isEmpty(value)){
            return Collections.emptyList();
        }
        return Arrays.asList(value.split(",")).stream().map(
                SimpleGrantedAuthority::new
        ).collect(Collectors.toList());
    }
}
